<template>

  <!-- 后台需求：
查看桌子
用户删除桌子
用户新增桌子，输入桌子编号，可选人数，生成二维码 -->
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.tableId" clearable class="filter-item" style="width: 160px;" placeholder="请输入桌号ID" />
      <el-input v-model="listQuery.userId" clearable class="filter-item" style="width: 160px;" placeholder="请输入商家ID" />
      <el-input v-model="listQuery.seatNumber" clearable class="filter-item" style="width: 160px;" placeholder="请输入座位容量" />
      <el-select slot="prepend" v-model="listQuery.isAvailable" clearable class="filter-item" style="width: 160px;" placeholder="请选择是否可用">
        <el-option label="可用" value="1" />
        <el-option label="不可用" value="0" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="桌子ID" prop="tableId" />

      <el-table-column align="center" min-width="100" label="桌子容量" prop="seatNumber" />

      <el-table-column align="center" label="商家ID" prop="userId" />

      <el-table-column align="center" label="是否在使用中" prop="state">
        <template slot-scope="scope">
          <el-tag
            effect="dark"
            :type="scope.row.state ? 'success' : 'error' "
          >{{ scope.row.state ? '在使用中' : '空闲' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否可用" prop="isAvailable">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isAvailable ? 'success' : 'error' ">{{ scope.row.isAvailable ? '可用' : '不可用' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="350" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="warning"
            size="mini"
            @click="qrcreate(scope.row)"
          >二维码</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          &nbsp&nbsp
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除吗？"
            @confirm="handleDelete(scope.row)"
          >
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 二维码对话框 -->
    <el-dialog
      :title="form.tableId.toString()"
      :visible.sync="dialogVisible"
      width="300px"
      @opened="openQrCode"
    >
      <div class="qrcode">
        <div id="qrcode" />
      </div>
      <div style="text-align:center" class="qrcodeBtn">
        <el-button type="primary" class="savetoloca" size="mini" @click="saveQrcode">保存到本地</el-button>
      </div>
    </el-dialog>

    <!-- 修改弹窗对话框 -->
    <el-dialog
      :flag="flag"
      title="编辑"
      :visible.sync="editVisible"
      width="30%"
      :before-close="handleClose"
    >
      <!-- form框 -->
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item
          label="桌号"
          prop="tableId"
        >
          <el-input v-model="form.tableId" :min="1" placeholder="请输入桌子序号" type="number" />
        </el-form-item>
        <el-form-item
          label="是否可用"
          prop="isAvailable"
        >
          <el-select v-model="form.isAvailable" type="number" placeholder="请选择">
            <el-option label="可用" :value="1" />
            <el-option label="不可用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="可入座最大人数"
          prop="seatNumber"
        >
          <el-input-number v-model="form.seatNumber" type="number" :min="1" :max="10" label="描述文字" @change="handleChange" />
        </el-form-item>
        <el-form-item
          label="状态"
          prop="state"
        >
          <el-select v-model="form.state" type="number" placeholder="请选择">
            <el-option label="正在使用" :value="1" />
            <el-option label="空闲" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="商家ID"
          prop="userId"
        >
          <el-input v-model="form.userId" type="number" :min="1" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">编辑</el-button>
          <el-button @click="resetForm('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <pagination v-show="size>0" :total="size" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

  </div>
</template>

<style>
  .table-expand {
    font-size: 0;
    padding-left: 60px;
  }
  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  .gallery {
    width: 80px;
    margin-right: 10px;
  }
  .goods-detail-box img {
    width: 100%;
  }
  .savetoloca{
  margin-top:20px;
  }
  .qrcode{
   display: table-cell;
   text-align: center;
   border: 1px solid #000;
  }
</style>

<script>
import { searchTables, updateTables, delteTables } from '@/api/table'
// import { statGoods } from '@/api/stat'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { thumbnail, toPreview } from '@/utils/index'
import QRCode from 'qrcodejs2'

export default {
  name: 'TableList',
  components: { BackToTop, Pagination },
  data() {
    return {
      form: {
        seatNumber: '',
        isAvailable: '',
        state: '',
        tableId: '',
        userId: ''
      },
      rules: {
        seatNumber: [
          { required: true, message: '请输入最大容量', trigger: 'change' }
        ],
        isAvailable: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        state: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        tableId: [
          { required: true, message: '请输入桌号ID', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请输入商家ID', trigger: 'blur' }
        ]
      },
      thumbnail,
      toPreview,
      list: [],
      size: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: 'add_time',
        order: 'desc'
      },
      flag: false,
      dialogVisible: false,
      editVisible: false,
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true

      // console.log("qqqqqqqqqqq")
      searchTables(this.listQuery).then(res => {
        console.log('wwwwwwwwwwww')
        console.log(this.listQuery, 'ppppppp')
        const dataList = res.data.data.list
        this.list = dataList
        this.size = res.data.data.size
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.size = 0
        this.listLoading = false
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.tableId) {
            updateTables(this.form).then(res => {
              this.$notify.success({
                title: '成功',
                message: '编辑成功'
              })
              this.editVisible = false
              // 刷新首页
              this.getList()
            }).catch(res => {
              this.$notify.error({
                title: '失败',
                message: '编辑失败'
              })
            })
          } else {
          }
        } else {
          this.$message.error('失败了！')
          return false
        }
      })
    },
    // handlechange
    handleChange(e) {
      console.log(e, 'change')
    },
    // 显示
    qrcreate(row) {
      this.dialogVisible = true
      this.form = row
      // 阻止冒泡
      if (row && row.preventDefault) {
        row.preventDefault()// 非IE浏览器
      } else { window.event.returnValue = false }
    },
    // 二维码
    openQrCode() {
      const tableCode = this.form.tableId
      document.getElementById('qrcode').innerHTML = ''
      const qrcode = new QRCode('qrcode', {
        width: 250,
        height: 250
      })
      const codeList = 'http://192.168.1.104:8081?tableId='
      qrcode.makeCode('http://192.168.1.104:8081/#/login/' + tableCode)
    },
    // 保存二维码
    saveQrcode() {
      // 找到canvas标签
      const myCanvas = document.getElementById('qrcode').getElementsByTagName('canvas')
      // 创建一个a标签节点
      const a = document.createElement('a')
      // 设置a标签的href属性（将canvas变成png图片）
      a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream')
      // 设置下载文件的名字
      const tableCode = this.form.tableId
      a.download = '座位' + tableCode + '.png'
      // 点击
      a.click()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.$router.push({ path: '/tables/add' })
    },
    handleUpdate(row) {
      this.form = row
      // console.log(this.form);
      this.editVisible = true
    },
    handleDelete(row) {
      const parmas = {
        'id': row.tableId
      }
      delteTables(parmas).then(response => {
        this.$notify.success({
          title: '成功',
          message: '删除成功'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['桌子ID', '容量', '名称', '状态', '商家ID', '是否可用']
        const filterVal = ['tableId', 'seatNumber', 'state', 'userId', 'isAvailable']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '商品信息')
        this.downloadLoading = false
      })
    },

    // 确认关闭弹窗
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          // 清空表单
          this.$refs.form.resetFields()
          this.editVisible = false
          this.resetClick()
        })
        .catch(_ => {})
    }
  }
}
</script>
